let products = [
  {
    id: 1001,
    name: "你是谁",
    img: "./img/mmexport1631069880346.jpg",
    price: 35.86,
  },
  {
    id: 1002,
    name: "我是谁",
    img: "./img/mmexport1631069880346.jpg",
    price: 35.45,
  },
  {
    id: 1003,
    name: "他是谁",
    img: "./img/mmexport1631069880346.jpg",
    price: 45.89,
  },
  {
    id: 1004,
    name: "谁是谁",
    img: "./img/mmexport1631069880346.jpg",
    price: 75.65,
  },
  {
    id: 1005,
    name: "她是谁",
    img: "./img/mmexport1631069880346.jpg",
    price: 66.99,
  },
];

let container = document.querySelector(".container");
console.log(container);
//商品列表显示
function showBook() {
  let Str = "";
  products.forEach((item) => {
    let bookStr = `
        <div class="item">
        <img src="${item.img}">
        <div class="name">书名：${item.name}</div>
        <p>介绍：好好好好好好好好爱护，一定要啊不是吧真的吗，哈哈哈，以你的心诠释我的爱....</p>
        价格:￥<span>${item.price}</span>
        <button type="button" date-index='${item.id}' >添加到购物车</button>
    </div>
        `;
    Str += bookStr;
  });
  container.innerHTML = Str;
}

showBook();

function addBook() {
  container.addEventListener("click", (e) => {
    e = e || window.event;
    let target = e.target || e.srcElement;
    if (target.nodeName == "BUTTON") {
      //找到当前点击的按钮id
      let id = target.getAttribute("date-index");
      //从数组中找到当前点击的那一条数据
      let product = products.find((item) => item.id == id);
      console.log('pr',product)
      //数组合并操作
      product = {
        ...product,
        num: 1,
        singlePrice: product.price,
        state: false,
      };
      // 把数据从localstorage中拿出来
      let carts = JSON.parse(localStorage.getItem("CartList")) || [];
      console.log(carts)
      let newProduct=carts.find(item=>item.id==product.id)
      //如果有了就给num++
      if(newProduct){ newProduct.num++ }
      //不在就添加到数据中
      else{carts.push(product)}
    }
    //把新的数组重新写回到localstorage中，覆盖前一个数组
    localStorage.setItem('CartList',JSON.stringify(carts))
    alert('添加购物车成功')
  });
}
addBook();
